var g_dev_cnt = 0;
var g_enable_cnt = 0;
var g_state_cnt = 0;
var g_set_cnt = 0;
var g_performance_cnt = 0;
var g_add_cnt = 0;
var g_cfr_cnt = 0;
var g_custom_cnt = 0;

/* 在删除之前需要询问是否真的需要删除相关的参数*/

function getLength(str) {
    var len = str.length;
    var reLen = 0;
    for (var i = 0; i < len; i++) {
        var tmp = str.charCodeAt(i);
        if (tmp < 27 || tmp > 126) {
            reLen += 2;
        } else {
            reLen++;
        }
    }
    return reLen;
}

function debug_display(msg_log) { //只适用于加载的静态目标的使用
    $("#head_msg").msg({ //头部请求的标签的位置信息
        type: 'warning',
        delay: 5000,
        text: msg_log
    });
}

function debug_display_success(msg_log) {
    $("#head_msg").msg({ //头部请求的标签的位置信息
        type: 'warning',
        delay: 5000,
        text: msg_log
    });
}

function ajax_requset(url_t, msg, func) {
    $.ajax({
        url: url_t,
        type: 'POST', //对数据的请求指令使用post的请求方式
        data: msg,
        success: function (data, status) {
            debug_display_success("从服务器成功请求回数据")
            func(data, status);
        },
        error: function (data, status) {
            var error_msg = "没有从服务器请求回相关的数据";
            debug_display(error_msg);
        }
    });
}

function update_paras_timer() {
    $("#time_update").html("<strong>" + date_update() + "</strong><br>");
}

function date_update() { //数据更新的时间戳,数据查询回来之后需要更新时间戳;通用功能节选
    var tmp = new Date();
    return tmp.getFullYear() + "-" + (tmp.getMonth() + 1) + "-" + tmp.getDate() + " " + tmp.getHours() + ":" + tmp.getMinutes() + ":" + tmp.getSeconds();
}

$(function () {
    $("#reboot_device").click(function () { //设备复位按键相应按钮,通过时间戳的响应;避免过长时间的等待;python3 中的打印加着换行符号;
        update_paras_timer();
        ajax_requset("/cgi-bin/cgi_user.py", "cmd=reboot", function (data, st) { //解析完成之后显示设备复位成功
            tmp = data.split("\n");
            res = tmp[1].split("=");
            if (res[1] == "reboot-successful") {
                alert("设备复位成功");
            }
        });
    })

    $('#cancel_para').click(function () {
        $(":checked").removeAttr("checked");
    })

    $('#update_para').click(function () {
        var str = "";
        var value;
        var tmp;
        str = "";
        str += "cmd=write";
        $(":checked").each(function () {
            str += "&";
            var st = $(this).attr("id").split("_");
            str += st[1];
            str += "=";
            value = $("#" + st[1]).val();
            var coeff = document.getElementById(st[1]).getAttribute("coefficient");
            var var_type = document.getElementById(st[1]).getAttribute("var_type");
            var type = var_type.indexOf("uint");
            if (type != -1) {
                tmp = parseFloat(value) * parseFloat(coeff);
            } else if (var_type.indexOf("sint1") != -1) {
                tmp = parseFloat(value);
                tmp = tmp * parseFloat(coeff);
                if (tmp < 0) {
                    tmp = 0 - tmp;
                    tmp = 0xff + 1 - tmp;
                }
            } else if (var_type.indexOf("sint2") != -1) {
                tmp = parseFloat(value);
                tmp = tmp * parseFloat(coeff);
                if (tmp < 0) {
                    tmp = 0 - tmp;
                    tmp = 0xffff + 1 - tmp;
                }
            } else if (var_type.indexOf("sint4") != -1) {
                tmp = parseFloat(value);
                tmp = tmp * parseFloat(coeff);
                if (tmp < 0) {
                    tmp = 0 - tmp;
                    tmp = 0xffffffff + 1 - tmp;
                }
            } else {
                tmp = value;
            }
            str += tmp;
        });
        $.post("/cgi-bin/cgi_user.py",
            str,
            function (data, status) {
                //alert("数据：" + data + "\n状态：" + status);
                if (status == "success") {
                    alert("设置成功");
                }
            });
    })

    function load_paras() {
        var use_flag = 1;
        var num;
        var tab_tmp;
        var str = "";
        g_dev_cnt = 0;
        g_enable_cnt = 0;
        g_state_cnt = 0;
        g_set_cnt = 0;
        g_performance_cnt = 0;
        g_add_cnt = 0;
        g_custom_cnt = 0;
        $("#ip_set").empty();
        $("#init_set").empty();
        $("#ir_set").empty();
        $("#radio_set").empty();
        $("#common_set").empty();

        //清除未被.empty清空过的 其他页面中含有的使用"append"添加的元素，而不影响原本元素
        $(".ap").each(function () {
            $(this).remove();
        });

        str = "cmd=para_list&nodata";
        $.post("/cgi-bin/cgi_user.py",
            str,
            function (data, status) {
                var clean_data = data.split("\n");
                data = "";
                data = clean_data[1];
                console.log(data);
                if (status == "success") {
                    var ss = data.split("&");
                    var sm = ss[0].split("=");
                    if ((sm[0] == "cmd") && (sm[1] == "para_list")) {
                        for (var i = 1; i < ss.length; i++) {
                            var st = ss[i].split("=");
                            num = parseInt(st[0], 16);
                            //选取id填入不同的tab页面中
                            if(use_flag == 0) {
                                if ((num <= 0x024) || ((num >= 0x601) && (num <= 0x607)) || ((num >= 0x101) && (num <= 0x166))) {
                                    tab_tmp = "ip_set";
                                    g_dev_cnt += 1;
                                    g_dev_cnt &= 1;
                                    tmp = g_dev_cnt;
                                } else if (((num >= 0x200) && (num <= 0x0300)) || ((num >= 0x30) && (num <= 0x49))) {
                                    tab_tmp = "init_set";
                                    g_enable_cnt += 1;
                                    g_enable_cnt &= 1;
                                    tmp = g_enable_cnt;
                                } else if (((num >= 0x301) && (num <= 0x0400)) || ((num >= 0x5c) && (num <= 0x75))) {
                                    tab_tmp = "radio_set";
                                    g_state_cnt += 1;
                                    g_state_cnt &= 1;
                                    tmp = g_state_cnt;
                                } else if (((num >= 0x400) && (num <= 0x0460)) || ((num >= 0x860) && (num <= 0x872))
                                    || ((num >= 0x172) && (num <= 0x185) || ((num >= 0x608) && (num <= 0x613)))) {
                                    tab_tmp = "common_set";
                                    g_set_cnt += 1;
                                    g_set_cnt &= 1;
                                    tmp = g_set_cnt;
                                } else if (((num >= 0x50e) && (num <= 0x050f)) || ((num >= 0x873) && (num <= 0x87c))) {
                                    tab_tmp = "common_set";
                                    //alert("ID：" + num.toString(16) + "\n");
                                    g_performance_cnt += 1;
                                    g_performance_cnt &= 1;
                                    tmp = g_performance_cnt;
                                } else if ((num >= 0x08000000) && (num <= 0x08000fff)) {
                                    tab_tmp = "common_set";
                                    g_add_cnt += 1;
                                    g_add_cnt &= 1;
                                    tmp = g_add_cnt;
                                } else if ((num >= 0x08800000) && (num <= 0x08800fff)) {
                                    tab_tmp = "common_set";
                                    //alert("ID：" + num.toString(16) + "\n");
                                    g_cfr_cnt += 1;
                                    g_cfr_cnt &= 1;
                                    tmp = g_cfr_cnt;
                                } else if (num == 0x900) {
                                    tab_tmp = "DL_passiveIM_detection";
                                } else {
                                    tab_tmp = "common_set"; //写入到通用配置界面
                                    g_custom_cnt += 1;
                                    g_custom_cnt &= 1;
                                    tmp = g_custom_cnt;
                                }
                            }else if(use_flag == 1){ //原始数据表的使用和修改
                                if((num => 0) && ( num <= 0xFFFFFFFF)){
                                    tab_tmp = "common_set";
                                    g_custom_cnt += 1;
                                    g_custom_cnt &= 1;
                                    tmp = g_custom_cnt;
                                }
                            }
                            //每个使用append添加的新元素，添加class属性为"ap",用于重新获取监控列表时清空, 定向定点绘画
                            var type_coef = st[1].split(",");
                            $("#" + tab_tmp).append("<b><input type='checkbox' id='cb_" + st[0] + "' class='ap'></b>");
                            $("#" + tab_tmp).append("<b><label style='width:250px; display:inline-block;' class='ap'>" + type_coef[0] + "</label></b>");
                            $("#" + tab_tmp).append("<b class='ap'>: <input class='c_para' type='text' id='" + st[0] + "' var_type='" + type_coef[1] + "' coefficient='" + type_coef[2] + "'></b>");
                            if (tmp == 0) {
                                $("#" + tab_tmp).append("<br class='ap'/>");
                            } else {
                                $("#" + tab_tmp).append("<b class='ap'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b>");
                            }
                        }
                        ("重新获取参量列表成功");
                    } else {
                        console.log(data); //控制台打印参数信息;
                    }
                }
            });
    }
    load_paras();

    $("#set_para_reload").click(function () {
        location.reload();
    })
    //读取全部参数;获取以往的参数ID值进行比对,兼容以前旧网页的操作方式
    $('#get_all_para').click(function () {
        var str = "";
        str += "cmd=read&nodata";
        $.post("/cgi-bin/cgi_user.py",
            str,
            function (data, status) {
                var clean_data = data.split("\n");
                data = "";
                data = clean_data[1];
                console.log(data);
                if (status == "success") {
                    var ss = data.split("&");
                    var sm = ss[0].split("=");
                    if ((sm[0] == "cmd") && (sm[1] == "read")) { //将获得的参数进行解析,解析完成后重新填入
                        for (var i = 1; i < ss.length; i++) {
                            var st = ss[i].split("=");
                            console.log("Index: "+st[0]);
                            var coeff = document.getElementById(st[0]).getAttribute("coefficient");
                            var var_type = document.getElementById(st[0]).getAttribute("var_type");
                            var type = var_type.indexOf("uint");
                            if (type != -1) {
                                $("#" + st[0]).val(parseFloat(st[1]) / parseFloat(coeff));
                            } else if (var_type.indexOf("sint1") != -1) {
                                var tmp = parseInt(st[1]);
                                if (tmp > 0x7f) {
                                    tmp = 256 - tmp;
                                    tmp = 0 - tmp;
                                }
                                $("#" + st[0]).val(tmp / parseFloat(coeff));
                            } else if (var_type.indexOf("sint2") != -1) {
                                var tmp = parseInt(st[1]);
                                if (tmp > 0x7fff) {
                                    tmp = 0xffff + 1 - tmp;
                                    tmp = 0 - tmp;
                                }
                                $("#" + st[0]).val(tmp / parseFloat(coeff));
                            } else if (var_type.indexOf("sint4") != -1) {
                                var tmp = parseInt(st[1]);
                                if (tmp > 0x7fffffff) {
                                    tmp = 0xffffffff + 1 - tmp;
                                    tmp = 0 - tmp;
                                }
                                $("#" + st[0]).val(tmp / parseFloat(coeff));
                            } else {
                                $("#" + st[0]).val(st[1]);
                            }
                        }
                        alert("查询成功并返回");
                    } else {
                        alert("查询失败: "+data);
                    }
                }
            });
    })
})